/**
 * Created by xiangyufang on 2016/10/8.
 */
;(function($,window,document,undefined){
    /***全局变量初始化 start***/
    var $table = $('#JQ_table').checkbox3();
    var DTTABLE;
    var $avoidEval = $('#JQ_search_eval');
    /***全局变量初始化 end***/

    /***表单条件初始化 start***/
    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title:'管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title:'终点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment,'beginSignId':$begin}
    });
    // 管道值改变时触发事件
    $pipeline.element.on('select',function(e,v){
        var id = v || $pipeline.val();
        if(id){
            // 管段
            DyyBase.ajax(cleanPipeApi.url_clean_segment(), {pipeLineId:id}, function(dataset){
                if(dataset.bool){
                    var json = DyyBase.getSelect(dataset.result);
                    $segment.add(json);
                }
            },{async:false});
            // 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginEnd(), {pipeLineId:id}, function(dataset){
                var beginEndData = dataset.result;
                var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                var end = DyyBase.getNewPos(beginEndData,'end',true);
                $begin.asset(begin);
                $end.asset(end);
            },{async:false});
        }else{
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
        $avoidEval.text('0');
    });
    // 管段值改变时触发事件
    $segment.element.on('select',function(e,v){
        var id = v || $segment.val();
        if(id){
            // 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginSegmentEnd(), {pipeSegmentId:id}, function(dataset){
                var beginEndData = dataset.result;
                var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                var end = DyyBase.getNewPos(beginEndData,'end',true);
                $begin.asset(begin);
                $end.asset(end);
            },{async:false});
        }else{
            $begin.add([]);
            $end.add([]);
        }
        $avoidEval.text('0');
    });
    // 起点值改变时触发事件
    $begin.element.on('select',function(){
        $avoidEval.text('0');
    });
    // 终点值改变时触发事件
    $end.element.on('select',function(){
        $avoidEval.text('0');
    });
    //清管类型
    var $type = $('#JQ_type').select3();
    //清管数据请求
    DyyBase.ajax(cleanPipeApi.url_history_cleanType(),{}, function(dataset){
        var json = DyyBase.getSelect(dataset);
        $type.add(json);
    },{async:false});

    // 清管类型值改变时触发事件
    $type.element.on('select',function(){
        $avoidEval.text('0');
    });
    //时间值改变时触发事件
    $('#JQ_startTime').click(function(){
        $avoidEval.text('0');
    });
    $('#JQ_endTime').click(function(){
            $avoidEval.text('0');
    });
    /***表单条件初始化 end***/

    //**查询条件**
    var filter = {
        //查询条件
        getSearchVal: function(data){
            var filter = {};
            filter.mode = true;
            // 分页参数
            if (data) {
                if (data.start == 0) {
                    filter['jsonBean.pageNum'] = 1;
                } else {
                    filter['jsonBean.pageNum'] = data.start / 10 + 1;
                }
                filter['jsonBean.pageCount'] = data.length;
            }
            //管道参数
            filter.lineId = function(){
                var v = $pipeline.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //起点参数
            filter.beginMile = function(){
                var v = $begin.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v;
                }
                return '';
            }();
            //终点参数
            filter.endMile = function(){
                var v = $end.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v;
                }
                return '';
            }();
            //清管类型参数
            filter.pagType = function(){
                var v = $type.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //清管时间起
            filter.beginTime = function(){
                var v = $('#JQ_startTime').val();
                if(v){
                    return v;
                }
                return '';
            }();
            //清管时间止
            filter.endTime = function(){
                var v1 = $('#JQ_startTime').val();
                var v2 = $('#JQ_endTime').val();
                if(v2){
                    if(v1){
                        if(!(Dyy.checkDateLate(v1,v2))){
                            $('#JQ_endTime').TIP({content:'结束日期应晚于开始日期！'});
                            filter.mode = false;
                        }
                    }
                    return v2;
                }
                return '';
            }();
            return filter;
        },
        //评价条件
        getEvalVal: function(){
            var filter = {};
            filter.mode = true;
            //管道参数
            filter.lineId = function(){
                var v = $pipeline.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_pipeline').TIP({content:'管道名称不能为空！'});
                    filter.mode = false;
                }
            }();
            //起点参数
            filter.beginMile = function(){
                var v = $begin.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_begin').TIP({content:'起点位置不能为空！'});
                    filter.mode = false;
                }
            }();
            //终点参数
            filter.endMile = function(){
                var v = $end.val();
                if(v){
                    return v;
                }else{
                    $('#JQ_end').TIP({content:'终点位置不能为空！'});
                    filter.mode = false;
                }
            }();
            //清管类型参数
            filter.pagType = function(){
                var v = $type.val('text');
                if(v){
                    return v;
                }else{
                    $('#JQ_type').TIP({content:'清管类型不能为空！'});
                    filter.mode = false;
                }
            }();
            return filter;
        },
        //复选框数据选择
        getCheckData: function(){
            var $checks = $table.find('i.zy-checkbox');
            //数组储存id
            var arr = [];
             $checks.each(function () {
             var $this = $(this);
             if ($this.hasClass('active')) {
             arr.push($this.attr('data-id'));
             }
             });
             return arr;
        }
    };

    //**表格数据**
    DTTABLE = $table.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页',
            'zeroRecords': DyyBase.table_empty(),
            'infoEmpty': ''
        },
        'autoWidth': false,
        'order': [],
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function (data, callback) {
            var param = filter.getSearchVal(data);
            DyyBase.ajax(cleanPipeApi.url_clean_history(), param, function (dataset) {
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.total;
                returnData.recordsFiltered = dataset.result.total;
                returnData.data = DyyBase.clearNull(dataset.result.list);
                callback(returnData);
                $("#JQ_check_all").attr('data-chk', 'false').removeClass('active');
            });
        },
        'drawCallback': function () {
        },
        'columns': [
            {
                data: 'id',
                render: function (data) {
                    return '<i class="zy-checkbox" data-id="' + data + '" title="选中"></i>';
                }
            },
            {
                data: 'taskName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'lineName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'fromPigName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'toPigName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'sendBallsTime',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'createUser',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'staus',
                render: function (data) {
                    if(data == '3'){
                        return '<span id="'+ data + '"  title="进行中">进行中</span>';
                    }else if(data == '2'){
                        return '<span id="'+ data + '"  title="已发布">已发布</span>';
                    }else if(data == '4'){
                        return '<span id="'+ data + '"  title="已完成">已完成</span>';
                    }else if(data == "1"){
                        return '<span id="'+ data + '"  title="未发布">未发布</span>';
                    }else{
                        return '<span id="'+ data + '"  title="状态未知">状态未知</span>';
                    }
                }
            },
            {
                data: 'id',
                render: function (data) {
                    return '<i data-a="' + data + '" class="zy-details-icon" title="展开详情"></i>';
                }
            },
            {
                data: 'id',
                render: function (data,type,row) {
                    return '<i data-a="' + data + '" data-name="'+ row.taskName + '" class="xyf-enclosure-icon" title="附件"></i>';
                }
            }
        ]
    });


    //跳转到详情页面
    $table.delegate('i.zy-details-icon','click',function(event){
        var $this = $(this);
        var Id = $this.attr("data-a");
        var url = cleanPipeApi.url_history_toDetail() + '?taskId=' + Id;
        window.location.href = url;
        event.stopPropagation();
    });

    //下载附件
    var $download_form = $('#JQ_download_form');
    $table.on("click","i.xyf-enclosure-icon",function(event){
        var $this = $(this);
        var id = $this.attr("data-a");
        var taskName = $this.attr("data-name");
        $download_form.empty();
        var $input = $('<input type="hidden" name="businessId" value="'+ id + '">');
        var $input2 = $('<input type="hidden" name="downFileName" value="'+ taskName + '的附件">');
        var $input3 = $('<input type="hidden" name="type" value="piggingTaskAtt">');
        $download_form.append($input).append($input2).append($input3);
        $download_form.submit();

        $('#JQ_action_iframe').get(0).onload = function(){
            var content = this.contentWindow.document.body.innerHTML;
            content = $.parseJSON(content);
            if(!content.bool){
                $this.MSG({
                    type: 'error',
                    content: content.result
                });
            }
        };

        event.stopPropagation();
    });


    //**查询**
    $('#JQ_search').click(function(){
        var param = filter.getSearchVal();
        if(param.mode){
            if(DTTABLE){
                DTTABLE.draw();
                $avoidEval.text('1');
            }
        }
    });

    //**评价**
    $('#JQ_evaluate').click(function(){
        var judge = filter.getEvalVal();
        var param = filter.getCheckData();
        var avoid_eval = $avoidEval.text();
        if(judge.mode){
            if(avoid_eval == '1'){
                if(param !=''){
                    var ids = '';
                    for(var i=0;i<param.length;i++){
                        ids += '&ids='+ param[i];
                    }
                    var url = cleanPipeApi.url_history_toEvaluation()+'?pile=' + judge.lineId +ids;
                    window.location.href = url;
                }else{
                    $(this).MSG({
                        content: '请勾选需要评价的任务！'
                    });
                    return false;
                }
            }else if(avoid_eval == '0'){
                $('#JQ_search').TIP({content:'请先点击查询获取数据列表!'});
                return false;
            }
        }
    })

})(jQuery,window,document);